<template>
    <div class="purchase-stats-page">
      <!-- 顶部信息卡片 -->
      <div class="info-card">
        <div class="info-content">
          <div class="info-image">
            <img src="/banner2.jpg" alt="用户购买次数分布分析" />
          </div>
          <div class="info-text">
            <h2>📊 用户购买次数分布分析</h2>
            <p class="desc">
              本图展示了用户在平台上的购买次数分布情况，通过对“一次性购买者”“多次购买者”以及“高频购买者”的比例进行分析，帮助我们了解不同类型用户的结构组成。
              <br /><br />
              从整体趋势来看，一次性购买的用户占比较大，是平台用户基础的主要来源；而多次购买和高频购买的用户虽然占比相对较小，但贡献了更高的销售额和复购价值。
              <br /><br />
              通过对用户购买次数分布的研究，品牌方可以针对不同类型用户设计差异化的营销策略，例如加强一次性用户的留存转化、提升中等频次用户的复购率，并为高频用户提供更具价值的会员服务和个性化推荐。
            </p>
          </div>
        </div>
      </div>
  
      <!-- 饼图 -->
      <div class="chart-card">
        <div ref="chartRef" class="chart-container"></div>
        <p class="note">饼图展示了各购买次数区间用户的占比（按人数统计）</p>
      </div>
  
      <!-- 下载按钮 -->
      <div class="download-wrapper">
        <button class="download-btn" :disabled="!chartInstance" @click="downloadChart">
          下载图表文件
        </button>
      </div>
  
      <!-- 页面底部 -->
      <FooterInfo />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import FooterInfo from '../components/FooterInfo.vue'
  import axios from 'axios'
  
  const chartRef = ref(null)
  const chartInstance = ref(null)
  const apiData = ref([])
  
  const API_BASE = 'http://localhost:8080/queryUserPurchaseStats'
  
  async function fetchData() {
    try {
      const { data: res } = await axios.get(API_BASE)
      apiData.value = res?.code === 200 ? res.data : []
      updateChart()
    } catch (err) {
      console.error('请求失败：', err)
      apiData.value = []
      updateChart()
    }
  }
  
  function updateChart() {
    if (!chartInstance.value) return
    if (!apiData.value || apiData.value.length === 0) {
      chartInstance.value.clear()
      return
    }
  
    const pieData = apiData.value.map(d => ({
      name: d.purchaseTimes,
      value: d.count,
      proportion: d.proportion
    }))
  
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: params => {
          return `
            购买次数：${params.name}<br/>
            用户数：${params.value.toLocaleString()}<br/>
            占比：${params.data.proportion}%
          `
        }
      },
      legend: {
        orient: 'horizontal',
        top: 0
      },
      series: [
        {
          name: '用户购买次数',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            formatter: '{b}\n{d}%'
          },
          labelLine: {
            show: true
          },
          data: pieData
        }
      ]
    }
  
    chartInstance.value.setOption(option)
  }
  
  onMounted(async () => {
    await nextTick()
    if (!chartRef.value) return
    chartInstance.value = echarts.init(chartRef.value)
    fetchData()
  
    window.addEventListener('resize', () => {
      chartInstance.value && chartInstance.value.resize()
    })
  })
  
  function downloadChart() {
    if (!chartInstance.value) return
    const url = chartInstance.value.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = url
    link.download = 'user-purchase-distribution.png'
    link.click()
  }
  </script>
  
  <style scoped>
  .purchase-stats-page {
    max-width: 1000px;
    margin: 40px auto;
    font-family: 'Segoe UI', sans-serif;
  }
  
  .info-card {
    background: #fff;
    padding: 25px 30px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    margin-bottom: 25px;
  }
  .info-content {
    display: flex;
    align-items: flex-start;
    gap: 20px;
  }
  .info-image img {
    width: 240px;
    height: auto;
    border-radius: 8px;
    object-fit: cover;
    margin-top: 70px;
  }
  .info-text {
    flex: 1;
  }
  .info-text h2 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 12px;
    color: #333;
  }
  .info-text .desc {
    font-size: 15px;
    color: #555;
    line-height: 1.8;
    text-align: justify;
  }
  
  .chart-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    padding: 20px;
    margin-bottom: 20px;
  }
  .chart-container {
    width: 100%;
    height: 500px;
  }
  .note {
    text-align: center;
    font-size: 13px;
    color: #888;
    margin-top: 10px;
  }
  
  .download-wrapper {
    text-align: center;
    margin-bottom: 30px;
  }
  .download-btn {
    background: #5470C6;
    color: #fff;
    padding: 10px 22px;
    border: none;
    border-radius: 6px;
    font-size: 15px;
    cursor: pointer;
    transition: background 0.3s;
  }
  .download-btn:hover {
    background: #3b5ba4;
  }
  .download-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  </style>
  